package com.my.concurrency.threadpool;

import com.my.concurrency.threadpool.task.MyTask;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @author: marshal
 * @date: 2023-07-24 10:15 AM
 */
@Slf4j
public class ScheduledThreadPoolExecutorTest {
    public static void main(String[] args) {
//       test1();
//        test2();
        test3();
    }

    /**
     * 基础使用
     */
    public static void test1() {
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10);
        log.debug("start.");
        executor.schedule(() -> {
            log.debug("This is delay task");
        }, 10, TimeUnit.SECONDS);
    }

    private static void test2() {
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10);
        log.debug("start.");
        IntStream.range(0, 5).boxed().toList().forEach(e -> {
            executor.schedule(new MyTask(e), (int) (Math.random() * 10), TimeUnit.SECONDS);
        });
    }

    /**
     * 固定频率执行
     */
    public static void test3() {
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10);
        log.debug("start.");
        executor.scheduleAtFixedRate(() -> {
            log.debug("This is delay task");
        }, 20, 10, TimeUnit.SECONDS);
    }

}
